package com.sinosoft.cloud.bl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sinosoft.cloud.annotation.ReqJsonBean;
import com.sinosoft.cloud.configuration.JsonMakerContainer;
import com.sinosoft.cloud.rest.TradeInfo;
import com.sinosoft.lis.entity.PolFactorPojo;
import com.sinosoft.lis.entity.PolResultPojo;
import com.sinosoft.utility.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

@Component
public class GetTbResultBL extends AbstractBL {

    @Value("${cloud.access.url}")
    String access_url;

    @Value("${cloud.test.control}")
    String test_control;


    Log log = LogFactory.getLog(GetTbResultBL.class);
    JsonMakerContainer jsonMakerContainer = JsonMakerContainer.getInstance();

    public TradeInfo dealData(TradeInfo tradeInfo) {

        log.info("前端传入的投保数据：：：" + tradeInfo.toJson());
        ReqJsonBean reqJsonBean = getReqJsonBean(tradeInfo);
        if (reqJsonBean == null) {
            log.error("不支持的交易类型");
            tradeInfo.addError("不支持的交易类型");
            return tradeInfo;
        }
        ArrayList<PolFactorPojo> polFactorPojos = (ArrayList<PolFactorPojo>) tradeInfo.getData(PolFactorPojo.class.getName());
        if (polFactorPojos != null && polFactorPojos.size() > 0) {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            int i = 0;
            ArrayList<PolResultPojo> resultPojos = new ArrayList<>();
            for (PolFactorPojo pojo : polFactorPojos) {
                i++;
                TradeInfo tradeInfo1 = new TradeInfo();
                tradeInfo1.addData(PolFactorPojo.class.getName(), pojo);
                String reqJson = reqJsonBean.request(tradeInfo1);
                log.info("请求报文：：：" + reqJson);
                String result = "";
                try {
                    if ("true".equals(test_control)) {
                        result = test(i);
                    } else {
                        log.info("统一接入地址：："+access_url);

                        result = restTemplate.postForObject(access_url, reqJson, String.class);
                    }
                } catch (Exception e) {
                    log.error("请求异常::::"+ ExceptionUtils.exceptionToString(e));
                    tradeInfo.addError("请求统一接入异常");
                    return tradeInfo;
                }
                PolResultPojo polResultPojo = new PolResultPojo();
                polResultPojo.setAppName(pojo.getAppntName());
                JSONObject jsonObject = JSON.parseObject(result);
                JSONObject response = (JSONObject) jsonObject.get("response");
                JSONObject header = (JSONObject) response.get("header");
                JSONObject body = (JSONObject) response.get("body");
                String success = body.getString("success");
                polResultPojo.setSuccess(success);
                if("0".equals(success)){
                    String errorCode = body.getString("errorCode");
                    polResultPojo.setErrorCode(errorCode);
                }
                String errorMessage = body.getString("errorMessage");
                polResultPojo.setErrorMessage(errorMessage);
                String policyNo = body.getString("policyNo");
                polResultPojo.setPolicyNo(policyNo);
                String outPolicyNo = body.getString("outPolicyNo");
                polResultPojo.setOutPolicyNo(outPolicyNo);
                String policyUrl = body.getString("policyUrl");
                polResultPojo.setPolicyUrl(policyUrl);
                log.info("返回报文：：：" + result);
                pojo.setResultJson(result.replaceAll("\n", " "));
                resultPojos.add(polResultPojo);
            }
            tradeInfo.clearData();
            tradeInfo.addData(PolResultPojo.class.getName(),resultPojos);
        }
        return tradeInfo;
    }

    private ReqJsonBean getReqJsonBean(TradeInfo tradeInfo) {
        String service_type = (String) tradeInfo.getData("serviceType");
        switch (service_type.toLowerCase()) {
            case "ant-pol":
                return jsonMakerContainer.getJsonBean("ANTPOL");
            case "ant-uw":
                return jsonMakerContainer.getJsonBean("ANTUW");
            case "ant-xq":
                return jsonMakerContainer.getJsonBean("ANTXQ");
            case "ant-xb":
                return jsonMakerContainer.getJsonBean("ANTXB");
            case "people-uw":
                return jsonMakerContainer.getJsonBean("PEOPLEUW");
            default:
                return null;
        }
    }

    String test(int i) {
        String succ = "{\n" +
                "\t\"response\" : {\n" +
                "\t\t\"header\" : {\n" +
                "\t\t\t\"version\" : \"1.0.0\",\n" +
                "\t\t\t\"function\" : \"ant.bxcloud.info.issueNotify_batch\",\n" +
                "\t\t\t\"transTime\" : 20181128092421,\n" +
                "\t\t\t\"transTimeZone\" : \"UTC+8\",\n" +
                "\t\t\t\"reqMsgId\" : 20181129113503211185,\n" +
                "\t\t\t\"format\" : \"json\",\n" +
                "\t\t\t\"signType\" : \"RSA\",\n" +
                "\t\t\t\"asyn\" : 0,\n" +
                "\t\t\t\"cid\" : \"PICC\"\n" +
                "\t\t},\n" +
                "\t\t\"body\" : {\n" +
                "\t\t\t\"success\" : 1,\n" +
                "\t\t\t\"errorMessage\" : \"交易成功\",\n" +
                "\t\t\t\"policyNo\" : 18112853182344010336,\n" +
                "\t\t\t\"outPolicyNo\" : \"20181129027329E\",\n" +
                "\t\t\t\"policyUrl\" : null\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}";
        String fail = "{\n" +
                "\t\"response\" : {\n" +
                "\t\t\"header\" : {\n" +
                "\t\t\t\"version\" : \"1.0.0\",\n" +
                "\t\t\t\"function\" : \"ant.bxcloud.info.issueNotify_batch\",\n" +
                "\t\t\t\"transTime\" : 20181128092421,\n" +
                "\t\t\t\"transTimeZone\" : \"UTC+8\",\n" +
                "\t\t\t\"reqMsgId\" : 20181129092603798101,\n" +
                "\t\t\t\"format\" : \"json\",\n" +
                "\t\t\t\"signType\" : \"RSA\",\n" +
                "\t\t\t\"asyn\" : 0,\n" +
                "\t\t\t\"cid\" : \"PICC\"\n" +
                "\t\t},\n" +
                "\t\t\"body\" : {\n" +
                "\t\t\t\"success\" : 0,\n" +
                "\t\t\t\"errorCode\" : \"AE10316060002005\",\n" +
                "\t\t\t\"errorMessage\" : \"MSE0501004-保单传入保费（19.08）与计算所得保费（24.92）不一致\",\n" +
                "\t\t\t\"policyNo\" : 18112853182344010336,\n" +
                "\t\t\t\"outPolicyNo\" : null,\n" +
                "\t\t\t\"policyUrl\" : null\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}";
        if (i % 2 == 0) {
            return succ;
        }
        return fail;
    }

    public static void main(String[] args) {
        String url = "http://10.130.128.92/antfin/json";
        String json = "{\"request\":{\"header\":{\"transTime\":\"2018-11-30 14:00:00\",\"function\":\"ant.bxcloud.info.issueNotify\",\"transTimeZone\":\"UTC+8\",\"format\":\"json\",\"signType\":\"RSA\",\"asyn\":\"0\",\"version\":\"1.0.0\",\"reqMsgId\":\"201811301511521543561912029143344\",\"cid\":\"PICC\"},\"body\":{\"prodNo\":\"6348\",\"effectStartTime\":\"20181201140000\",\"issueTime\":\"20181130140000\",\"insureds\":{\"birthday\":\"\",\"certType\":\"100\",\"gender\":\"\",\"medicalInsurance\":\"\",\"waitingPeriod\":\"\",\"certNo\":\"130682199101124076\",\"nationality\":\"CH\",\"phone\":\"\",\"certName\":\"张三\",\"pronounceName\":\"\",\"personNo\":\"18031550020545420321\",\"relationWithHolder\":\"1\",\"email\":\"\"},\"outBizNo\":\"20181130151152155801333\",\"coverageList\":{\"copiesCount\":\"1\",\"premium\":\"5000\",\"sumInsured\":\"56415313\",\"effectStartTime\":\"20181201140000\",\"effectEndTime\":\"2018412170903\",\"coverageNo\":\"F0080100001000036977\",\"csuNo\":\"6704_1\"},\"policyNo\":\"182256509406\",\"effectEndTime\":\"20181201140000\",\"holder\":{\"birthday\":\"\",\"certNo\":\"130682199101124076\",\"certType\":\"100\",\"gender\":\"\",\"nationality\":\"CH\",\"phone\":\"\",\"certName\":\"张三\",\"pronounceName\":\"\",\"personNo\":\"18031550020545320321\",\"email\":\"\"},\"applyNum\":\"2\",\"instSerialNo\":\"20181130ZAOL3075186771\",\"premium\":\"10700\",\"sumInsured\":\"12000000\",\"policyType\":\"2\",\"bills\":{\"merchantAccountType\":\"1\",\"payTime\":\"2018412170903\",\"otherAccountId\":\"2088302224968066\",\"fee\":\"50000\",\"otherAccountType\":\"1\",\"merchantAccountId\":\"2088101164965391\",\"payFlowId\":\"2018031510002001060204830643\",\"billNo\":\"18031550015984040320\"},\"insuredTime\":\"20181130\",\"actualPremium\":\"10700\"}},\"signature\":\"QX01D/2hIHNQTF6xj9tVnZhn72SZ29azvxUcjeztZiXYQcQdGwR89dvTaHltndv2j44GqEgOawUcyW2asbLH1eCVLdUW3L2R8QboBw66zEwpegvhG8Owvoc0fSSGlWG9EMF7IfIe70zqMW8euWvgU8r9ij7zDKU+rGMUg+JWR0UMPZexO5Ue5DHjXtkkhsvr/0IvgJFf0wRQx0E0XiCK4ZMwq+6EJ56SQjuaqRD/NBuxTtqKf5lBe2UhGb4YsmSPdnyMcjvVKjByY+xBdv1FK+xw1q965HR8GYC1V4PZ0CkjJHViWjAAeHARfxFLBlnGsFA8Z8B84Zqctefn1lNnUA==\"}";
        RestTemplate restTemplate = new RestTemplate();
        String s = restTemplate.postForObject(url, json, String.class);
        System.out.println(s);
    }

}
